package net.pulseproject.router.config.instantiator.builder;

import java.util.Collection;
import java.util.LinkedHashSet;

import net.pulseproject.router.config.instantiator.builder.validator.FieldValidator;
import net.pulseproject.router.config.instantiator.builder.validator.SkeletonFieldValidator;
import net.pulseproject.router.modules.Module;

public abstract class Builder<T extends Module> {
	
	private String id;
	
	private final Collection<FieldValidator> validators = new LinkedHashSet<FieldValidator>();
	
	private final FieldValidator validator = new SkeletonFieldValidator() {
		@Override
		protected void validateFields() {
			if(Builder.this.getId() == null) {
				throw new RuntimeException("id not yet set");
			}
		}
	};
	
	
	public Builder() {
		this.validators.add(this.validator);
	}
	
	protected final void addValidator(final FieldValidator newValidator) {
		this.validators.add(newValidator);
	}
	
	public final void setId(final String id) {
		this.id = id;
	}
	
	protected final String getId() {
		return this.id;
	}
	
	protected abstract T buildModule();
	
	public final T build() {
		for (final FieldValidator currentValidator : this.validators) {
			currentValidator.validate();
		}
		
		return this.buildModule();
	}

}
